import React from "react";

import cs from "classnames";
import qs from "query-string";
import sty from "./sty.module.css";

import SongInfo from "./child/songInfo";
import SongComment from "./child/songComment";
import SongItem from "./child/songItem";
import { getSizeImage, handleMinSec } from "@/utils/format-utils";
import { reqLyric, reqSongDetail, reqRelatedSongList } from "@/api/song";
import { memo } from "react";

import { useState } from "react";
import { useEffect } from "react";
import { parseLyric } from "@/utils/parse-lyric";
import { Skeleton } from "antd";
import { useMemo } from "react";
const Song = memo((props) => {
  const [songsList, setSongsList] = useState([]);
  const [lyric, setLyric] = useState([]);
  const [songDetail, setSongDetail] = useState({});
  const { id } = qs.parse(props.location.search);
  useEffect(() => {
    loadSongDetail(id);
    loadLyric(id);
    loadRelated(id);
  }, [id]);
  const loadSongDetail = async (id) => {
    const res = await reqSongDetail(id);
    let song = res && res.songs[0];
    song = {
      pirUrl: song.al.picUrl,
      songName: song.name,
      singer: song.ar[0].name,
      album: song.al.name,
      id: song.id,
    };
    setSongDetail(song);
  };
  const loadLyric = async (id) => {
    const res = await reqLyric(id);
    let lyric = res.lrc && res.lrc.lyric;
    if (lyric) {
      lyric = parseLyric(lyric);
      setLyric(lyric);
    }
  };
  const loadRelated = (id) => {
    reqRelatedSongList(id).then((res) => {
      if (res.code === 200) {
        let songs = res.songs;
        songs = songs.map((v, i) => {
          return {
            index: i + 1,
            duration: handleMinSec(v.dt),
            songName: v.name,
            singer: v.artists[0].name,
            songId: v.id,
            coverPic: getSizeImage(v.album.picUrl, 50) || "",
          };
        });
        setSongsList(songs);
      }
    });
  };
  const songId = useMemo(() => id, [id]);
  const lyricList = useMemo(() => lyric, [lyric]);
  const info = useMemo(() => songDetail, [songDetail]);
  return (
    <div className={cs("wrap2", "songBg", "flex1")}>
      <div className={sty.left}>
        <SongInfo songDetail={info} lyric={lyricList} />
        <SongComment songId={songId} />
      </div>
      <ul className={sty.right}>
        {songsList.length ? (
          songsList.map((v) => <SongItem key={v.songId} {...v} />)
        ) : (
          <Skeleton active />
        )}
      </ul>
    </div>
  );
});
export default Song;
